//
//  XTXLuzhiyuyinViewController.m
//  陪我V聊
//
//  Created by 余清巍 on 2018/7/25.
//  Copyright © 2018年 陪我V聊. All rights reserved.
//

#import "XTXLuzhiyuyinViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <QuartzCore/QuartzCore.h>
@interface XTXLuzhiyuyinViewController ()<AVAudioPlayerDelegate>{
    NSTimer *Timer;
    NSInteger timeCount;
    NSInteger judge;//判断
    NSString *filePath;
    MBProgressHUD *HUD;
    NSInteger counter1;
}
@property (nonatomic,strong) UILabel *shijianLabel;//时间
@property (nonatomic,strong) UILabel *fanweuLabel;//范围
@property (nonatomic,strong) UIButton *luzhianniu;//录制按钮
@property (nonatomic,strong) UILabel *luzhiwenziLabel;//录制文字
@property (nonatomic,strong) UIButton *chongxinluzhiBtn;//重新录制
@property (nonatomic,strong) UIButton *fasongBtn;//发送
@property (nonatomic,strong) UILabel *czLabel;//范围
@property (nonatomic,strong) UILabel *wcLabel;//范围
@property (nonatomic, strong) AVAudioSession *session;
@property (nonatomic, strong) AVAudioRecorder *recorder;//录音器
@property (nonatomic, strong) AVAudioPlayer *player; //播放器
@property (nonatomic, strong) NSURL *recordFileUrl; //文件地址

@end

@implementation XTXLuzhiyuyinViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self infrastructure];
    [self jiemiandajian];
    [self bujuyueshushezhi];
}
-(void)jiemiandajian{
    [self.view addSubview:self.shijianLabel];
    [self.view addSubview:self.fanweuLabel];
    [self.view addSubview:self.luzhianniu];
    [self.view addSubview:self.luzhiwenziLabel];
    [self.view addSubview:self.chongxinluzhiBtn];
    [self.view addSubview:self.fasongBtn];
    [self.view addSubview:self.czLabel];
    [self.view addSubview:self.wcLabel];
    _chongxinluzhiBtn.hidden = YES;
    _fasongBtn.hidden = YES;
    self.czLabel.hidden = YES;
    self.wcLabel.hidden = YES;
    [self createAnimationWithDuration:0.35 delay:1];
}
- (CABasicAnimation *)createAnimationWithDuration:(CGFloat)duration delay:(CGFloat)delay {
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    anim.fromValue = [NSNumber numberWithFloat:0.0f];
    anim.toValue = [NSNumber numberWithFloat:1.0f];
    anim.autoreverses = YES;
    anim.duration = duration;
    anim.removedOnCompletion = NO;
    anim.beginTime = CACurrentMediaTime()+delay;
    anim.repeatCount = INFINITY;
    anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    return anim;
}
-(void)bujuyueshushezhi{
    _shijianLabel.sd_layout.heightIs(155.0).widthIs(155.0).topSpaceToView(self.view, iOS_H(180)+zhuangtaiDaohangGao).centerXEqualToView(self.view);
    _fanweuLabel.sd_layout.leftSpaceToView(self.view, 0).rightSpaceToView(self.view, 0).centerXEqualToView(self.view).topSpaceToView(_shijianLabel, iOS_H(70)).heightIs(iOS_H(30));
    _luzhianniu.sd_layout.widthIs(90).heightIs(90).centerXEqualToView(self.view).bottomSpaceToView(self.view, iOS_H(220));
    _luzhiwenziLabel.sd_layout.heightIs(iOS_H(28)).widthIs(App_Frame_Width/2).topSpaceToView(_luzhianniu, iOS_H(50)).centerXEqualToView(self.view);
    _chongxinluzhiBtn.sd_layout.widthIs(iOS_W(100)).heightIs(iOS_W(100)).centerYEqualToView(_luzhianniu).leftSpaceToView(self.view, iOS_W(80));
    _fasongBtn.sd_layout.widthIs(iOS_W(100)).heightIs(iOS_W(100)).centerYEqualToView(_luzhianniu).rightSpaceToView(self.view, iOS_W(80));
    self.czLabel.sd_layout.widthIs(80.0).heightIs(40.0).centerXEqualToView(self.chongxinluzhiBtn).topSpaceToView(self.chongxinluzhiBtn, 0);
    self.wcLabel.sd_layout.widthIs(80.0).heightIs(40.0).centerXEqualToView(self.fasongBtn).topSpaceToView(self.fasongBtn, 0);
    [self createCircleWithRadius:0.23 color:UIColor.clearColor positionX:0];
}
- (UIView *)createCircleWithRadius:(CGFloat)radius
                             color:(UIColor *)color
                         positionX:(CGFloat)x {
    UIView *circle = [[UIView alloc] initWithFrame:CGRectMake(x, 0, radius * 2, radius * 2)];
    circle.backgroundColor = color;
    circle.layer.cornerRadius = radius;
    circle.translatesAutoresizingMaskIntoConstraints = NO;
    return circle;
}
-(void)infrastructure{
    self.view.backgroundColor = XZColor(240, 240, 240);
    self.title = @"录制语音";
    //登陆按钮
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"后退按钮"] landscapeImagePhone:[UIImage imageNamed:@"后退按钮"] style:UIBarButtonItemStylePlain target:self action:@selector(fanhuishijian)];
    backItem.tintColor = [UIColor blackColor];
    self.navigationItem.leftBarButtonItem = backItem;
    
}
- (void)paomaAnimate:(BOOL)isStop{
    
    if (!isStop) {
        UILabel* lbindex0 = [UILabel new];
        UILabel* lbindex1 = [UILabel new];
        
        [UIView transitionWithView:self.view duration:0.25 options:UIViewAnimationOptionCurveLinear animations:^{
            lbindex0.frame = CGRectMake(-20, 0, 30, 50);
            lbindex1.frame = CGRectMake(lbindex0.frame.origin.x+lbindex0.frame.size.width, 0, lbindex1.frame.size.width, lbindex1.frame.size.height);
            
        } completion:^(BOOL finished) {
            lbindex0.frame = CGRectMake(-20, 0, 30, 50);
            lbindex1.frame = CGRectMake(-20, 0, 30, 50);
            [self performSelector:@selector(start) withObject:nil afterDelay:2];
        }];
    }
}



- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [_luzhianniu setBackgroundImage:[UIImage imageNamed:@"录制完成-播放语音"] forState:UIControlStateNormal];
    judge=2;
}
- (void)start{
    [self paomaAnimate:YES];
}
//返回
-(void)fanhuishijian{
    [self.player stop];
    [self.navigationController popViewControllerAnimated:YES];
}

//录制的秒数
-(void)timing{
    timeCount++;
     _shijianLabel.text = [NSString stringWithFormat:@"%ld\"",(long)timeCount];
    if (timeCount==60) {
        [Timer invalidate];
        Timer = nil;
        _chongxinluzhiBtn.hidden = NO;
        _fasongBtn.hidden = NO;
        self.czLabel.hidden = NO;
        self.wcLabel.hidden = NO;
        _luzhiwenziLabel.text = @"";
        [_luzhianniu setBackgroundImage:[UIImage imageNamed:@"录制完成-播放语音"] forState:UIControlStateNormal];
        counter1 = timeCount;
        timeCount=0;
        judge=2;
        if ([self.recorder isRecording]) {
            [self.recorder stop];
        }
    }
    [self dictionaryForKey:@"wilbeginsoruy" create:YES];
}
- (NSMutableDictionary *)dictionaryForKey:(NSString *)key
                                   create:(BOOL)create
{
    NSMutableDictionary *dictionary = nil;
    id object = [NSMutableDictionary dictionary];

    if (object) {
        if ([object isKindOfClass:[NSMutableDictionary class]]) {
            dictionary = (NSMutableDictionary *)object;
        } else {
            dictionary = [object mutableCopy];
           
        }
    } else if (create) {
        dictionary = [NSMutableDictionary dictionary];
       
    }

    return dictionary;
}
//录制
-(void)luzhianniudedianjishijianClick{
    if (judge==0) {
        Timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timing) userInfo:nil repeats:YES];
        _luzhiwenziLabel.text = @"正在录制，点击停止";
        [_luzhianniu setBackgroundImage:[UIImage imageNamed:@"语音-录制中"] forState:UIControlStateNormal];
        judge=1;
        [self kaishiluzhidedianjishijianClick];
    }else if (judge==1){
        if (timeCount>=10) {
            [Timer invalidate];
            Timer = nil;
            _chongxinluzhiBtn.hidden = NO;
            _fasongBtn.hidden = NO;
            self.czLabel.hidden = NO;
            self.wcLabel.hidden = NO;
            _luzhiwenziLabel.text = @"录制完成，点击播放";
            [_luzhianniu setBackgroundImage:[UIImage imageNamed:@"录制完成-播放语音"] forState:UIControlStateNormal];
            counter1 = timeCount;
            timeCount=0;
            judge=2;
            //停止录音
            if ([self.recorder isRecording]) {
                [self.recorder stop];
            }
        }else{
            [XTXTool showError:@"录制时间必须大于10秒！"];
        }
    }else if (judge==2){
        //播放语音条
        [_luzhianniu setBackgroundImage:[UIImage imageNamed:@"语音-录制中"] forState:UIControlStateNormal];
        judge=3;
            self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.recordFileUrl error:nil];
            self.player.delegate = self;
            [self.session setCategory:AVAudioSessionCategoryPlayback error:nil];
            [self.player play];
    }else if (judge==3){
         [_luzhianniu setBackgroundImage:[UIImage imageNamed:@"录制完成-播放语音"] forState:UIControlStateNormal];
        judge=2;
            [self.player stop];
    }
    
    [self allowRead:NO key:@"NSNumber"];
}
-(void)allowRead:(BOOL)allowed
             key:(NSString *)key
{
    NSMutableDictionary * data = [self dictionaryForKey:key create:allowed];
    if (allowed)
    {
        [data setObject:[NSNumber numberWithBool:allowed] forKey:@"NSNumber"];
    }
    else
    {
        [data removeObjectForKey:@"NSNumber"];
    }
}

//重新录制
-(void)chongxinluzhianniudedianjishijian{
    [self.player stop];
    _chongxinluzhiBtn.hidden = YES;
    _fasongBtn.hidden = YES;
    self.czLabel.hidden = YES;
    self.wcLabel.hidden = YES;
    [_luzhianniu setBackgroundImage:[UIImage imageNamed:@"录制语音-默认状态"] forState:UIControlStateNormal];
    _luzhiwenziLabel.text = @"开始录制";
    judge=0;
    [self allowWrite:NO key:@"create"];
}
-(void)allowWrite:(BOOL)allowed
              key:(NSString *)key
{
    NSMutableDictionary * data = [self dictionaryForKey:key create:allowed];
    if (allowed)
    {
        [data setObject:[NSNumber numberWithBool:allowed] forKey:@"create"];
    }
    else
    {
        

        [data removeObjectForKey:@"create"];
    }
}
//开始录制
-(void)kaishiluzhidedianjishijianClick{
    AVAudioSession *session =[AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    if (session == nil) {
        //NSLog(@"Error creating session: %@",[sessionError description]);
    }else{
        [session setActive:YES error:nil];
    }
    self.session = session;
    //1.获取沙盒地址
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    filePath = [path stringByAppendingString:@"/RRecord.wav"];
    //2.获取文件路径
    self.recordFileUrl = [NSURL fileURLWithPath:filePath];
    //设置参数
    NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                                   //采样率  8000/11025/22050/44100/96000（影响音频的质量）
                                   [NSNumber numberWithFloat: 8000.0],AVSampleRateKey,
                                   // 音频格式
                                   [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                                   //采样位数  8、16、24、32 默认为16
                                   [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                   // 音频通道数 1 或 2
                                   [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
                                   //录音质量
                                   [NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey,
                                   nil];
    _recorder = [[AVAudioRecorder alloc] initWithURL:self.recordFileUrl settings:recordSetting error:nil];
    if (_recorder) {
        _recorder.meteringEnabled = YES;
        [_recorder prepareToRecord];
        [_recorder record];
    }else{
        //NSLog(@"音频格式和文件存储格式不匹配,无法初始化Recorder");
        [self jsonDictionary:@{}];
    }
    
}
-(NSDictionary *)jsonDictionary:(NSDictionary *)additionalDeviceInfo
{
    NSMutableDictionary * deviceInfo = [NSMutableDictionary dictionary];
    [deviceInfo addEntriesFromDictionary:additionalDeviceInfo];
    NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithDictionary:@{@"events": @{@"launch": @"launch",
                                                                                              @"terminate": @"terminate",
                                                                                              @"event": @"event"},
                                                                                 @"device": deviceInfo}];
    
    if (deviceInfo!=nil) {
        
        [dict setObject:@"customInfo" forKey:@"customInfo"];
    }
    return dict;
}
//发送
-(void)fasonganniudedianjishijian{
    [self.player stop];
    [self yinpingshangchuangdewangluoqingqiuClick];
    [self clearAllCache];
}
-(BOOL)clearAllCache {
    BOOL __block success;
   NSString *path = [NSFileManager.defaultManager contentsOfDirectoryAtPath:@"//skw/sie/a.mp4" error:nil].firstObject;
    success = [[NSFileManager defaultManager] removeItemAtPath:path error:NULL];
    // ignore create diectory error
    [[NSFileManager defaultManager] createDirectoryAtPath:path
                              withIntermediateDirectories:YES
                                               attributes:nil
                                                    error:NULL];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
    return success;
}
-(void)yinpingshangchuangdewangluoqingqiuClick
{
    WeakSelf
    NSData *fileData = [NSData dataWithContentsOfURL:self.recordFileUrl];
    [XTXNetworking networkingUpUseVoicedewangluoqingqiu:fileData completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] integerValue] == 1) {
            [weakSelf upUseVoiceEvee2:dict[@"info"][@"voiceUrl"]];
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [XTXGongView showTipMsg:dict[@"msg"]];
            });
        }
    }];
}

- (void)orientationChanged:(NSNotification *)notification
{
    
    UIInterfaceOrientation o = (UIInterfaceOrientation)[[UIApplication sharedApplication] statusBarOrientation];
    CGFloat angle = 0;
    switch (o) {
        case UIDeviceOrientationLandscapeLeft: angle = 90; break;
        case UIDeviceOrientationLandscapeRight: angle = -90; break;
        case UIDeviceOrientationPortraitUpsideDown: angle = 180; break;
        default: break;
    }

    CGRect f = [[UIScreen mainScreen] applicationFrame];

    // Swap the frame height and width if necessary
     if (UIDeviceOrientationIsLandscape(o)) {
        CGFloat t;
        t = f.size.width;
        f.size.width = f.size.height;
        f.size.height = t;
    }

    CGAffineTransform previousTransform = self.view.layer.affineTransform;
    CGAffineTransform newTransform = CGAffineTransformMakeRotation((CGFloat)(angle * M_PI / 180.0));

    // Reset the transform so we can set the size
    self.view.layer.affineTransform = CGAffineTransformIdentity;
    self.view.frame = (CGRect){ { 0, 0 }, f.size};

    // Revert to the previous transform for correct animation
    self.view.layer.affineTransform = previousTransform;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    // Set the new transform
    self.view.layer.affineTransform = newTransform;

    // Fix the view origin
    self.view.frame = (CGRect){ { f.origin.x, f.origin.y },self.view.frame.size};
    [UIView commitAnimations];
}

-(void)upUseVoiceEvee2:(NSString *) voiceUrl
{
    NSMutableDictionary *tempMutDict = [NSMutableDictionary dictionary];
    tempMutDict[@"pack"] = APPLink;
    tempMutDict[@"id"] = XTXGongTool.share.useMode.id;
    tempMutDict[@"voiceexamineing"] =  voiceUrl;
    tempMutDict[@"voicetimeexamineing"] = [NSString stringWithFormat:@"%ld",counter1];
    WeakSelf
    [XTXNetworking networkingUpUseVoice2dewangluoqingqiu:tempMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([dict[@"code"] isEqualToString:@"1"]) {
                [XTXGongView showTipMsg:@"提交成功"];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
            else {
                [XTXGongView showTipMsg:dict[@"msg"]];
                [self showToView];
            }
        });
    }];
}

- (void)showToView{
    UIView *mainView = [[UIView alloc] init];
    mainView.backgroundColor = [UIColor blackColor];
    mainView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    mainView.frame = [UIScreen mainScreen].bounds;
    UIView *mainBgView = [[UIView alloc] init];
    mainBgView.alpha = 0.0;
    mainBgView.backgroundColor = [UIColor blackColor];
    mainBgView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    mainBgView.frame = [UIScreen mainScreen].bounds;
    [mainView addSubview:mainBgView];
    
    __block UIImageView *toImageView = nil;
    
    __block UIImageView *imageView = [[UIImageView alloc] init];
    imageView.userInteractionEnabled = YES;
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    [mainBgView addSubview:imageView];
    mainView.clipsToBounds = YES;
    
    UIImage *thumbImage = nil;
    
    if (thumbImage == nil) {
        thumbImage = toImageView.image;
    }
    if (thumbImage == nil) {
        imageView.image = toImageView.image;
    }else{
        imageView.image = thumbImage;
    }
    
}




-(UILabel *)shijianLabel{
    if (!_shijianLabel) {
        _shijianLabel = [[UILabel alloc]init];
        _shijianLabel.textColor = XZRGB(0xff6464);
        _shijianLabel.textAlignment = NSTextAlignmentCenter;
        _shijianLabel.font = [UIFont systemFontOfSize:35];
        _shijianLabel.layer.borderColor = XZColor(228, 228, 228).CGColor;
        _shijianLabel.layer.borderWidth = 10.0;
        _shijianLabel.layer.cornerRadius = 155.0/2;
        _shijianLabel.layer.masksToBounds = YES;
        _shijianLabel.backgroundColor = UIColor.whiteColor;
        _shijianLabel.text = @"0\"";
    }
    return _shijianLabel;
}
-(UILabel *)fanweuLabel{
    if (!_fanweuLabel) {
        _fanweuLabel = [[UILabel alloc]init];
        _fanweuLabel.textColor = XZColor(255, 109, 109);
        _fanweuLabel.textAlignment = NSTextAlignmentCenter;
        _fanweuLabel.font = [UIFont systemFontOfSize:iOS_W(30)];
        _fanweuLabel.text = @"———————— 5~60秒之间 ————————";
        _fanweuLabel.hidden = YES;
    }
    return _fanweuLabel;
}
-(UILabel *)luzhiwenziLabel{
    if (!_luzhiwenziLabel) {
        _luzhiwenziLabel = [[UILabel alloc]init];
        _luzhiwenziLabel.textColor = XZRGB(0xaaaaaa);
        _luzhiwenziLabel.textAlignment = NSTextAlignmentCenter;
        _luzhiwenziLabel.font = [UIFont systemFontOfSize:14.0];
        _luzhiwenziLabel.text = @"点击开始录制，10~60秒语音";
    }
    return _luzhiwenziLabel;
}

-(UIButton *)luzhianniu{
    if (!_luzhianniu) {
        _luzhianniu = [UIButton new];
        [_luzhianniu setBackgroundImage:[UIImage imageNamed:@"录制语音-默认状态"] forState:UIControlStateNormal];
        [_luzhianniu addTarget:self action:@selector(luzhianniudedianjishijianClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _luzhianniu;
}
-(UIButton *)chongxinluzhiBtn{
    if (!_chongxinluzhiBtn) {
        _chongxinluzhiBtn = [UIButton new];
        [_chongxinluzhiBtn setBackgroundImage:[UIImage imageNamed:@"重置语音"] forState:UIControlStateNormal];
        [_chongxinluzhiBtn addTarget:self action:@selector(chongxinluzhianniudedianjishijian) forControlEvents:UIControlEventTouchUpInside];
    }
    return _chongxinluzhiBtn;
}
-(UIButton *)fasongBtn{
    if (!_fasongBtn) {
        _fasongBtn = [UIButton new];
        [_fasongBtn setBackgroundImage:[UIImage imageNamed:@"完成"] forState:UIControlStateNormal];
        [_fasongBtn addTarget:self action:@selector(fasonganniudedianjishijian) forControlEvents:UIControlEventTouchUpInside];
    }
    return _fasongBtn;
}

- (UILabel *)czLabel
{
    if (!_czLabel) {
        _czLabel = [[UILabel alloc] init];
        _czLabel.text = @"重置";
        _czLabel.textColor = XZRGB(0x646464);
        _czLabel.font = [UIFont systemFontOfSize:13.0];
        _czLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _czLabel;
}

- (UILabel *)wcLabel
{
    if (!_wcLabel) {
        _wcLabel = [[UILabel alloc] init];
        _wcLabel.text = @"完成";
        _wcLabel.textColor = XZRGB(0x646464);
        _wcLabel.font = [UIFont systemFontOfSize:13.0];
        _wcLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _wcLabel;
}

@end
